package com.ntd.study.base.thread;

import cn.hutool.core.lang.Console;
import ntd.util.UtilThread;

import java.util.concurrent.locks.*;

/**
 * lock - 显示锁
 * 1.同步锁 Lock - lock（） 上锁 - unlock() 释放锁
 * 2.可中断锁 - Lock 有多种方式可以获取锁，不一定一直阻塞等待
 * 3.可以判断锁状态
 * 4.可以设置为公平锁 - 构造方法传true
 */
public class DemoThreadLock2 {
    final static Lock lock = new ReentrantLock();
    final static Condition condition = lock.newCondition();
    private static int tick = 100;
    static Runnable runnable = () -> {
        lock.lock();
        try {
            while (true) {
                if (tick > 0) {
                    UtilThread.sleep(500);
                    condition.await();
                    Console.log(Thread.currentThread().getName() + ":" + --tick);
                } else {
                    Console.log(Thread.currentThread().getName() + "结果:" + tick);
                    return;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        condition.signalAll();
    };

    public static void main(String[] args) {
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }

    /**
     * 读写/写写 需要互斥
     * 读读不需要互斥
     */
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
}
